package com.jn.erp.web.api.student.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jn.erp.common.core.page.TableDataInfo;
import com.jn.erp.common.core.result.AjaxResult;
import com.jn.erp.common.utils.StringUtils;
import com.jn.erp.security.controller.BaseWebAuthController;
import com.jn.erp.web.api.common.enums.ErrorEnum;
import com.jn.erp.web.api.course.task.TCourseOrderTask;
import com.jn.erp.web.api.student.entity.StudentClass;
import com.jn.erp.web.api.student.entity.TStudentClassRela;
import com.jn.erp.web.api.student.entity.dto.StudentClassDto;
import com.jn.erp.web.api.student.entity.dto.StudentClassListExcalDto;
import com.jn.erp.web.api.student.entity.dto.StudentListDto;
import com.jn.erp.web.api.student.entity.vo.StudentClassExcalVo;
import com.jn.erp.web.api.student.entity.vo.StudentClassVo;
import com.jn.erp.web.api.student.service.StudentClassRelaService;
import com.jn.erp.web.api.student.service.StudentClassService;
import com.jn.erp.web.api.student.service.StudentService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/tClass")
public class TClassController  extends BaseWebAuthController {
    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentClassService studentClassService;

    @Autowired
    private StudentClassRelaService studentClassRelaService;

    @Autowired
    private TCourseOrderTask tCourseOrderTask;
   /**
    * 班級新增
    * */
    @PostMapping("/save")
    public AjaxResult save(@RequestBody StudentClassVo studentClassVo) {

        //机构id
        studentClassVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        studentClassVo.setCreator(getUserId());
        studentClassVo.setDeleted(0);
        studentClassVo.setIsRepair(1);
        String code = studentClassService.saveClass(studentClassVo);
        return AjaxResult.success(code);
    }
    /**
     * 补课班级创建
     * */
    @PostMapping("/saveRepair")
    public AjaxResult saveRepair(@RequestBody StudentClassVo studentClassVo) {

        //机构id
        studentClassVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        studentClassVo.setCreator(getUserId());
        studentClassVo.setDeleted(0);
        StudentClass studentClass = studentClassService.getOne(new QueryWrapper<StudentClass>().eq("deleted", 0).eq("is_repair", 0).eq("course_id", studentClassVo.getCourseId()));
        if(Objects.isNull(studentClass)){
            studentClass = studentClassVo;
            studentClass.setName(studentClassVo.getCourseName()+"（补课班)");
            studentClass.setClassHour(1);
            studentClass.setIsRepair(0);
            studentClass.setBeOver(1L);
            studentClassService.save(studentClassVo);

        }
        return AjaxResult.success(studentClass);
    }


    /**
     * 班級修改--结业
     * */
    @PostMapping("/update")
    public AjaxResult update(@RequestBody StudentClassVo studentClassVo) {

        //机构id
        studentClassVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        studentClassVo.setEditor(getUserId());
        studentClassVo.setEditTime(LocalDateTime.now());
        studentClassVo.setDeleted(0);

        String code = studentClassService.updateClass(studentClassVo);

        return AjaxResult.success(code);
    }


    /**
     * 班級删除
     * */
    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody StudentClassVo studentClassVo) {

        //机构id
        studentClassVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        studentClassVo.setEditor(getUserId());
        studentClassVo.setEditTime(LocalDateTime.now());
        studentClassVo.setDeleted(1);
        Boolean boo = studentClassService.updateById(studentClassVo);
        return AjaxResult.success(boo);
    }


    /**
     * 班級列表
     * */
    @GetMapping("/list")
    public TableDataInfo list(StudentClassVo studentClassVo) {

        startPage();
        //机构id
        studentClassVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        studentClassVo.setCreator(getUserId() );

        if(!Objects.isNull(studentClassVo.getIfMine()) && studentClassVo.getIfMine()==0){
            studentClassVo.setMine(getUserId());
        }
        List<StudentClassDto> list = studentClassService.classList(studentClassVo);
        return getDataTable(list);
    }

    /**
     * 班級详情
     * */
    @PostMapping("/getById")
    public AjaxResult getById(@RequestBody StudentClassVo studentClassVo) {
        //机构id
        studentClassVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        studentClassVo.setCreator(getUserId() );
        StudentClass studentClass = studentClassService.getClassById(studentClassVo);
        studentClass.setBeOver(null);
        return AjaxResult.success(studentClass);
    }

    /**
     * 导入--班级列表
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/importList")
    public AjaxResult importList(@RequestParam(value = "file") MultipartFile file) throws Exception {
        long l = Long.parseLong(loginDeptAuth());
        Long userId = getUserId();

        if (!file.isEmpty()) {
            // 处理导入逻辑
            logger.info("导入文件: {}", file.getOriginalFilename());
            ImportParams param = new ImportParams();
//            param.setHeadRows(2);
            List<StudentClassExcalVo> studentClassExcalVos = ExcelImportUtil.importExcel(file.getInputStream(), StudentClassExcalVo.class, param);
            studentClassExcalVos = studentClassExcalVos.stream().filter(u-> !StringUtils.isEmpty(u.getClassName())).collect(Collectors.toList());
            String code = studentClassService.importList(studentClassExcalVos,Long.parseLong(loginDeptAuth()),getUserId() );
            return AjaxResult.success(code);
        }
        return AjaxResult.success(  ErrorEnum.E104.getValue());
    }


    //导出--班级列表
    @RequestMapping("/exportClassList")
    public void exportClassList(@RequestBody StudentClassVo studentClassVo, HttpServletResponse response){
        //机构id
        studentClassVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        studentClassVo.setCreator(getUserId() );
        //1.查询数据
        List<StudentClassListExcalDto> studentClassListExcalDtos = studentClassService.exportClassList(studentClassVo);
        AtomicInteger i = new AtomicInteger(1);

        //2.封装成表格
        //参数1：表格标题，参数2：sheet名称
        ExportParams exportParams = new ExportParams(null, "班级信息");


        //参数1：表格参数  参数2：实体类  参数3：数据
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, StudentClassListExcalDto.class, studentClassListExcalDtos);
        //3.返回表格
        //设置表格文件名字
        String fileName = "班级信息";
        try {
            fileName = URLEncoder.encode(fileName, "UTF8");
            //设置返回数据类型
            response.setHeader("Access-Control-Expose-Headers", "content-disposition");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");

            //将表格输出
            OutputStream os = response.getOutputStream();
            sheets.write(os);
            os.close();
            os.flush();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 学生报读列表
     * */
    @GetMapping("/studentCourseList")
    public TableDataInfo studentCourseList(StudentClassVo studentClassVo) {
        startPage();
        //机构id
        studentClassVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        studentClassVo.setCreator(getUserId() );
        studentClassVo.setPOrgId(Long.parseLong(loginDeptParentAuth()) );
        List<StudentListDto> studentClass = studentClassService.studentCourseList(studentClassVo);
        return getDataTable(studentClass);
    }

    /**
     * 班级成员添加
     * */
    @PostMapping("/addStudentToClass")
    public AjaxResult addStudentToClass(@RequestBody List<TStudentClassRela> tStudentClassRelas) {
        tStudentClassRelas.stream().forEach(u->{

            //机构id
            u.setOrgId(Long.parseLong(loginDeptAuth()) );
            //当前登录人id
            u.setCreator(getUserId() );
            u.setAddTime(LocalDateTime.now());
            u.setDeleted(0);
        });
        String code = studentClassService.addStudentToClass(tStudentClassRelas,1);

        return AjaxResult.success(code);
    }
    /**
     * 班级成员添加(学院页)
     * */
    @PostMapping("/addStudentToClassSecond")
    public AjaxResult addStudentToClassSecond(@RequestBody List<TStudentClassRela> tStudentClassRelas) {
        tStudentClassRelas.stream().forEach(u->{

            //机构id
            u.setOrgId(Long.parseLong(loginDeptAuth()) );
            //当前登录人id
            u.setCreator(getUserId() );
            u.setAddTime(LocalDateTime.now());
            u.setDeleted(0);
        });
        String code = studentClassService.addStudentToClass(tStudentClassRelas,2);

        return AjaxResult.success(code);
    }

    /**
     * 班级成员列表
     * */
    @GetMapping("/studentList")
    public TableDataInfo studentList(StudentClassVo studentClassVo) {
        startPage();
        //机构id
        studentClassVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        studentClassVo.setCreator(getUserId() );
        List<StudentListDto> studentClass = studentClassService.studentList(studentClassVo);
        return getDataTable(studentClass);
    }

    /**
     * 移至其他班移除本班
     * */
    @PostMapping("/removeStudent")
    public AjaxResult removeStudent(@RequestBody TStudentClassRela tStudentClassRela) {
        //机构id
        tStudentClassRela.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tStudentClassRela.setEditor(getUserId() );
        tStudentClassRela.setEditTime(LocalDateTime.now() );
        String code = studentClassService.removeStudent(tStudentClassRela);
        return AjaxResult.success(code);
    }
}
